#
# Define
#
WEBSOCK_URL = 'ws://127.0.0.1:50080/'
#WEBSOCK_URL = 'ws://192.168.0.3:3000/'

g_streamer = null

#------------------
# On ready
#------------------
$ ->
  # create controller, player
  # @todo try catch
  g_streamer = new Controller()

  #
  # Controller's event handler
  #
  g_streamer.msg_authorized = (user)->
    console.log '[UI]authorized!!'
    console.log user

  g_streamer.msg_added_tune = (tune)->
    console.log '[UI]Adding tune comopleted.'
    console.log '[UI][tune] : ' + tune.name + ' owner=' + tune.owner_session_id

  g_streamer.msg_started_play = (tune)->
    console.log '[UI]started play : ' + tune.name
    console.log '[UI][tune] : req=' + tune.requester_session_id + ' owner=' + tune.owner_session_id

  g_streamer.msg_finished_publisher = ->
    console.log '[UI]Publisher finished!'

  g_streamer.msg_finished_subscribe = ->
   console.log '[UI]Subscriber finished!'



  #
  # User interaction handler
  #
  $('#btn-connect').click ->
    # @todo try catch
    g_streamer.authorize(WEBSOCK_URL)

  $('#btn-add-song').change (evt)->
    # @todo try catch
    audiofile = evt.target.files[0]
    console.log audiofile
    g_streamer.add_playlist(audiofile)

  $('#btn-play').click ->
    g_streamer.start_play(g_streamer.player.tune_list.tunes[0])

  $('#btn-send').click ->
    # array = new Float32Array(10)
    # for i in [0..10]
    #   array[i] = i * i / 3

    # for val in array
    #   console.log val

    # Uint8Array? : Type for other 
    # g_socket.send(new Uint8Array(array))

    #ab = new ArrayBuffer((10 * 4));
    #view = new DataView(ab);
    #offset = 0
    #for fval in array
    #  view.setFloat32(offset, fval)
    #  offset += 4;

    # ArrayBuffer : Type for mozilla 
    # packet = new StreamingPacket()
    # packet.create_empty_packet(array.length)
    # data = packet.to_array_buffer(123, 456, array)
    # g_socket.send(data)


  $('#btn-close').click ->
    g_streamer.finalize()

